<template>
    <div class="app-container" v-loading="loading">
        <levelbar></levelbar>
        <el-form label-width="100px" class="app-content" :rules="rules" :model="ruleForm" ref="ruleForm">
            <div class="box">
                <div class="appTitle">{{title}}</div>
                <div class="appTop">上传屏保</div>
                <el-row>             
                    <el-col class="imageBox" :span="24">
                        <el-form-item label="屏保图片：" class="el-form-star">
                            <image-upload @getImgName="getImgName"
                            v-model='ruleForm.dataScreen.sPicture' :imageSize="2"></image-upload>
                            <span class="imgNote">（推荐尺寸 1783*860，支持jpg、jpeg、png、bmp格式，大小不超过2M）</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row >
                    <el-col :span="12">
                        <el-form-item label="屏保文字：">
                            <el-input  placeholder="请输入屏保文字" v-model="ruleForm.dataScreen.sDesc" :maxlength="30"></el-input>
                        </el-form-item>
                        <el-form-item label="">
                            <el-checkbox v-model="ruleForm.checked">是否特定时间段展示</el-checkbox>
                        </el-form-item>
                        <el-form-item label="开始时间：" prop="startDate" v-if="ruleForm.checked">
                            <el-date-picker
                                :editable="false"
                                v-model="ruleForm.startDate"
                                type="datetime"
                                placeholder="请选择开始时间"
                                :picker-options="ruleForm.pickerOptions1"
                                format="yyyy-MM-dd HH:mm:ss"
                                @change="dateChange1"
                                style="width:100%"
                               >
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="结束时间：" prop="endDate" v-if="ruleForm.checked">
                            <el-date-picker
                                :editable="false"
                                v-model="ruleForm.endDate"
                                type="datetime"
                                placeholder="请选择结束时间"
                                :picker-options="ruleForm.pickerOptions2"
                                format="yyyy-MM-dd HH:mm:ss"
                                @change="dateChange2"
                                style="width:100%"
                                >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>  
                </el-row>

                <div class="footer">
                    <el-button  @click="goBack">返回</el-button>
                    <el-button type="primary" @click="saveScreen('ruleForm')">保 存</el-button>
                </div>
            </div>
        </el-form>
    </div>
</template>

<script>
import Levelbar from '../layout/Levelbar';
import imageUpload from 'components/Upload/imgUpload';
import startDate from 'components/Datepicker/startDate';
import endDate from 'components/Datepicker/endDate';
import {savePicture, getPicture, editPicture} from 'api/deviceManagement';
import { mapGetters } from 'vuex';
import moment from 'moment';

export default{
    name: 'addScreenImg',
    components: {Levelbar, imageUpload, startDate, endDate},
    data() {
        var validatePass = (rule, value, callback) => {
            callback();
        }; // 添加※号不验证

        // 验证规则
        var validStart = (rule, value, callback) => {
            if (value == '') {
                return callback(new Error('请选择开始时间')); 
            } else {
                let now = new Date();
                let time = now.getTime() - 60000; 
                if (value <= time) {
                    return callback(new Error('开始时间必须大于等于当前时间'));  
                }
                callback();
            }
        };
        var validEnd = (rule, value, callback) => {
            if (value == '') {
                return callback(new Error('请选择结束时间')); 
            } else {
                if (value < this.ruleForm.startDate) {
                    return callback(new Error('结束时间必须大于开始时间'));  
                }
                callback();   
            }
        };
        return {          
            loading: false,
            title: '添加图片',
            ruleForm: {
                picName: '', // 图片名字
                schoolId: '',
                checked: false, // 是否上传屏保 给后台时0是 1否
                carousel: '5', // 轮播时间
                lockScreen: '1', // 锁屏时间
                startDate: '',
                endDate: '',
                pickerOptions1: {
                    disabledDate(time) {
                        return time.getTime() < new Date().getTime() - 864e5 ;
                    }
                },
                pickerOptions2: {
                    disabledDate(time) {
                        return time.getTime() < new Date().getTime() - 864e5;
                    }
                },
                dataScreen: {
                    sDesc: '', // 屏保文字
                    sPicture: '', // 图片url
                    sPictureName: ''
                }
                // 屏保数据
            },
            rules: {
                schoolId: [
                    { required: true, message: '请选择学校', trigger: 'change' }
                ],
                imageUrl: [
                    { required: true, validator: validatePass }
                ],
                startDate: [
                    { type: 'date', required: true, message: '请选择开始时间', trigger: 'blur' },
                    { validator: validStart, trigger: 'change'}
                ],
                endDate: [
                    { type: 'date', required: true, message: '请选择结束时间', trigger: 'blur' },
                    { validator: validEnd, trigger: 'change'}
                ]
                
            }
        }
    },
    created() {
        if (this.$route.params.id) {
            this.title = '编辑图片';
            this.getScreen()
        } else {
            this.title = '添加图片'
        }
        
    },
    computed: {
        ...mapGetters([
            'schoolId'
        ])
    },
    methods: {
        // 获取上传的图片的名字
        getImgName(picName) {
            this.ruleForm.dataScreen.sPictureName=picName;
        },
        // 回填
        getScreen() {
            let json={
                pId: this.$route.params.id
            }
            getPicture(json).then(res => {
                let content=res.data.content;
                if (content) {
                    this.ruleForm.dataScreen.sDesc=content.desc;
                    this.ruleForm.dataScreen.sPicture=content.picture;
                    this.ruleForm.dataScreen.sPictureName=content.picName;
                    this.ruleForm.checked=content.sSpecialSee=='0'?true:content.sSpecialSee=='1'?false:false; // 是(0)否(1)特定时间展开
                    this.ruleForm.startDate=content.startTime?new Date(content.startTime):'';
                    this.ruleForm.endDate=content.endTime?new Date(content.endTime):'';
                }
            })
        },
        // 保存屏保
        saveScreen(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (!this.ruleForm.dataScreen.sPicture) {
                        this.$message({
                            type: 'error',
                            message: '请上传屏保图片'
                        });
                        return '';
                    }
                    this.$confirm('确定要保存屏保设置吗?', ' ', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消'
                    }).then(() => {
                        this.loading = true;
                        if (this.$route.params.id) {// 编辑
                            this._editPicture();// 编辑
                        } else {// 添加
                            this._savePicture();// /添加
                        }
                       
                    })
                }
            })
        },
        _editPicture() {
            let json={
                pId: this.$route.params.id,
                desc: this.ruleForm.dataScreen.sDesc,
                fSchoolId: this.$route.params.schoolId,
                picture: this.ruleForm.dataScreen.sPicture,
                picName: this.ruleForm.dataScreen.sPictureName,
                sSpecialSee: this.ruleForm.checked?0:1, // 是(0)否(1)特定时间展开
                startTime: this.ruleForm.startDate?moment(this.ruleForm.startDate).format('YYYY-MM-DD HH:mm:ss'):'', //
                endTime: this.ruleForm.endDate?moment(this.ruleForm.endDate).format('YYYY-MM-DD HH:mm:ss'):'' //
            }
            editPicture(json).then(response => {
                this.loading = false;
                this.$message({
                    type: 'success',
                    message: '编辑屏保成功'
                });
                this.$router.go(-1);
            }).catch(() => {
                this.loading = false;
            })
        },
        _savePicture() {
            let json={
                desc: this.ruleForm.dataScreen.sDesc,
                picture: this.ruleForm.dataScreen.sPicture,
                position: this.$route.params.sPosition,
                picName: this.ruleForm.dataScreen.sPictureName,
                fSchoolId: this.$route.params.schoolId,
                sSpecialSee: this.ruleForm.checked?0:1, // 是(0)否(1)特定时间展开
                startTime: this.ruleForm.startDate?moment(this.ruleForm.startDate).format('YYYY-MM-DD HH:mm:ss'):'', //
                endTime: this.ruleForm.endDate?moment(this.ruleForm.endDate).format('YYYY-MM-DD HH:mm:ss'):'' //
            }
            savePicture(json).then(response => {
                this.loading = false;
                this.$message({
                    type: 'success',
                    message: '保存屏保成功'
                });
                this.$router.go(-1);
            }).catch(() => {
                this.loading = false;
            })
        },
        // 功能：开始日期选择
        dateChange1(date) {
            this.ruleForm.pickerOptions2 = {
                disabledDate(time) {                    
                    return time.getTime() < new Date(date).getTime() - 864e5 || time.getTime() < new Date().getTime() - 864e5;
                }
            };
        },

        // 功能：结束日期选择
        dateChange2(date) {
            this.ruleForm.pickerOptions1 = {
                disabledDate(time) {                  
                    return time.getTime() > new Date(date).getTime() || time.getTime() < new Date().getTime() - 864e5;
                }
            };
        },
        goBack() {
            this.$router.go(-1);
        }
    }
}
</script>

<style lang="scss" scoped>
.app-container {
    position: relative;
    padding: 20px 20px 10px;
    .app-levelbar {
        height: 35px;
    }
    .el-form{
        box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
        -webkit-box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
        background:#fff;
        padding-bottom:100px;
        .appTop{
            position: relative;
            font-size: 14px;
            color: rgb(106, 85, 72);
            padding-left: 16px;
            margin: 30px 0;
            display: block;
            &::after {
                position: absolute;
                content:'';
                width: 4px;
                height: 14px;
                background: #ff5e2c;
                left: 0;
                top: 3px;
            }
        }
        .appTitle{
            padding-top:8px;
            text-align: center;
            font-size: 18px;
            color: #333;
            line-height: 72px;
            font-weight: bold;
            font-family: Microsoft YaHei;
            border-bottom: 1px solid #ddd;
        }
        .el-form-star{
            position: relative;
            &::before{
                position: absolute;
                content: '*';
                left: 0;
                top: 11px;
                color: #ff5e2c;
            }
            
        }
        .box{
            padding: 0px 50px;
            background:#fff;
        }
       .footer{
            text-align:center;
            margin-top:90px;
        }
        .setMinWith1{
            min-width: 160px;
        }
        .addBtn{
            margin:0px 0 50px 18px;
            font-size: 14px;
            color: #ff5e2c;
        }
        .imgNote{
            color: #ff5e2c;
            position: absolute;
            top: 0;
            left:180px;
        }
        .delBtn {
            font-size: 20px;
            color:#999;
            margin: 105px 0 0 100%;
        }
        .imageBox:nth-of-type(2n){
            margin-left:100px;
        }
        .isUpdataPb{
            margin:25px 0 40px 17px;
        }
        .UpdataPb{
            margin-bottom:15px;
        }
    }
    
}

</style>
